package app.kotlin_1.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by 刘智强 on 2017/10/20.
 * 文件操作工具
 */

public class FileUtils {
    private static String SDPATH;
    static {
        SDPATH = Environment.getExternalStorageDirectory() + File.separator;
    }


    /**
     * 在SD卡上创建文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public static File creatFileOnSD(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName
     * @return
     */
    public static File creatDirOnSD(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdir();
        return dir;
    }

    /**
     * 判断文件在SD卡上是否存在
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

    /**
     * 将输入流里的数据写入SD卡中
     *
     * @param path        写入文件存放路径
     * @param fileName    生成的文件名
     * @param inputStream 输入流
     * @return
     */
    public static File writData2SDFromInputStream(String path, String fileName, InputStream inputStream) {
        File file = null;
        OutputStream output = null;
        try {
            creatDirOnSD(path);
            file = creatFileOnSD(path + fileName);
            output = new FileOutputStream(file);
            //每4K输出一次
            byte buffer[] = new byte[4 * 1024];
            while (inputStream.read(buffer) != -1) {
                output.write(buffer);
            }
            //清除缓存
            output.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return file;
    }
}
